package com.cskaoyan.service.impl;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.chenfeng.vo.CategoryL1Vo;
import com.cskaoyan.bean.chenfeng.vo.CategorySimpleL1Vo;
import com.cskaoyan.bean.leihao.vo.GoodsCategoryVo;
import com.cskaoyan.bean.leihao.vo.HotGoodsListDTO;
import com.cskaoyan.bean.leihao.vo.WxGoodsListVo;
import com.cskaoyan.bean.chenfeng.vo.CategoryIndexVo;
import com.cskaoyan.bean.chenfeng.vo.CategoryL1Vo;
import com.cskaoyan.bean.chenfeng.vo.CategorySimpleL1Vo;
import com.cskaoyan.bean.chenfeng.vo.CurrentCategoryVo;
import com.cskaoyan.bean.param.CommonData;
import com.cskaoyan.mapper.MarketBrandMapper;
import com.cskaoyan.mapper.MarketCategoryMapper;
import com.cskaoyan.mapper.MarketGoodsMapper;
import com.cskaoyan.mapper.MarketSearchHistoryMapper;
import com.cskaoyan.service.CategoryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 商品类目Service接口实现类
 * [后台系统 → 商场管理 → 商品类目]
 *
 * @author Chen_Feng
 * @since 2022/06/26 20:45
 */
@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {

    @Value("${file.storage.origin}")
    String webAdress;

    @Autowired
    MarketCategoryMapper marketCategoryMapper;
    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketSearchHistoryMapper searchHistoryMapper;
    @Autowired
    MarketBrandMapper brandMapper;

    /**
     * 获取所有L1级别的商品类目，并获得其下所有子类类目
     *
     * @return com.cskaoyan.bean.param.CommonData<com.cskaoyan.bean.chenfeng.vo.CategoryL1Vo>
     * @author Chen_Feng
     * @since 2022/06/26 20:48
     */
    @Override
    public CommonData<CategoryL1Vo> getL1CategoryWithSub() {

        // 调用mapper操作数据库进行查询
        List<CategoryL1Vo> list = marketCategoryMapper.selectL1CategoryWithSub();

        // 处理图片路径
        for (CategoryL1Vo categoryL1Vo : list) {
            String picUrl = categoryL1Vo.getPicUrl();
            String iconUrl = categoryL1Vo.getIconUrl();
            if (!picUrl.startsWith("http://") && !picUrl.startsWith("https://")) {
                categoryL1Vo.setPicUrl(webAdress + picUrl);
            }
            if (!iconUrl.startsWith("http://") && !iconUrl.startsWith("https://")) {
                categoryL1Vo.setIconUrl(webAdress + iconUrl);
            }
            List<CategoryL1Vo.CategoryL2Vo> children = categoryL1Vo.getChildren();
            for (CategoryL1Vo.CategoryL2Vo child : children) {
                String childPicUrl = child.getPicUrl();
                String childIconUrl = child.getIconUrl();
                if (childPicUrl != null && !childPicUrl.startsWith("http://") && !childPicUrl.startsWith("https://")) {
                    child.setPicUrl(webAdress + childPicUrl);
                }
                if (childIconUrl != null && !childIconUrl.startsWith("http://") && !childIconUrl.startsWith("https://")) {
                    child.setIconUrl(webAdress + childIconUrl);
                }
            }
        }

        // 封装数据
        PageInfo<CategoryL1Vo> pageInfo = new PageInfo<>(list);
        return CommonData.data(pageInfo);
    }

    /**
     * 仅仅获得L1级别的商品类目
     *
     * @return com.cskaoyan.bean.param.CommonData<com.cskaoyan.bean.chenfeng.vo.CategorySimpleL1Vo>
     * @author Chen_Feng
     * @since 2022/06/26 21:29
     */
    @Override
    public CommonData<CategorySimpleL1Vo> getL1Category() {
        // 调用mapper操作数据库进行查询
        List<CategorySimpleL1Vo> list = marketCategoryMapper.selectL1Category();

        // 封装数据
        PageInfo<CategorySimpleL1Vo> pageInfo = new PageInfo<>(list);
        return CommonData.data(pageInfo);
    }

    /**
     * 判断该类目名称在其父类之下是否已经存在
     * 判断标准为是否存在未处于删除状态并且name与pid与传入的值相等的类目id
     * 存在则返回true，不存在返回false
     *
     * @param marketCategory 包含了要判断的商品类目的信息的对象
     * @return boolean
     * @author Chen_Feng
     * @since 2022/06/26 22:26
     */
    @Override
    public boolean isCategoryExist(MarketCategory marketCategory) {

        // 执行mapper操作
        Integer id = marketCategoryMapper.selectCategoryIdByNameAndPid(marketCategory.getName().trim(), marketCategory.getPid());
        return id != null && !Objects.equals(id, marketCategory.getId());
    }

    /**
     * 增加
     * 新增商品类目，之后返回附带自增主键的对象
     *
     * @param marketCategory 要新增的商品类目信息封装的对象
     * @return com.cskaoyan.bean.MarketCategory
     * @author Chen_Feng
     * @since 2022/06/26 22:46
     */
    @Override
    public MarketCategory createCategory(MarketCategory marketCategory) {

        // 获得sortOrder
        byte sortOrder = getSortOrder(marketCategory);

        // 数据预处理
        if (Objects.equals(marketCategory.getLevel(), "L1")) {
            marketCategory.setPid(0);
        }
        Date date = new Date();
        marketCategory.setSortOrder(sortOrder);
        marketCategory.setAddTime(date);
        marketCategory.setUpdateTime(date);
        marketCategory.setDeleted(false);

        // 图片路径处理
        String originIconUrl = marketCategory.getIconUrl();
        String originPicUrl = marketCategory.getPicUrl();
        marketCategory.setIconUrl(originIconUrl.replace(webAdress, ""));
        marketCategory.setPicUrl(originPicUrl.replace(webAdress, ""));

        // 执行mapper操作
        marketCategoryMapper.insertSelective(marketCategory);

        // 图片再处理
        marketCategory.setIconUrl(originIconUrl);
        marketCategory.setPicUrl(originPicUrl);

        return marketCategory;
    }

    /**
     * 修改
     * 修改商品类目信息
     *
     * @param marketCategory
     * @return boolean
     * @author Chen_Feng
     * @since 2022/06/26 23:17
     */
    @Override
    public boolean updateMarketCategory(MarketCategory marketCategory) {
        // 获取sortOrder
        byte sortOrder = getSortOrder(marketCategory);

        // 数据预处理
        if (Objects.equals(marketCategory.getLevel(), "L1")) {
            marketCategory.setPid(0);
        }
        Date date = new Date();
        marketCategory.setSortOrder(sortOrder);
        marketCategory.setUpdateTime(date);
        marketCategory.setDeleted(false);

        // 图片路径处理
        String originIconUrl = marketCategory.getIconUrl();
        String originPicUrl = marketCategory.getPicUrl();
        marketCategory.setIconUrl(originIconUrl.replace(webAdress, ""));
        marketCategory.setPicUrl(originPicUrl.replace(webAdress, ""));

        // 执行mapper操作
        int affectedRows = marketCategoryMapper.updateByPrimaryKeySelective(marketCategory);

        // 图片再处理
        marketCategory.setIconUrl(originIconUrl);
        marketCategory.setPicUrl(originPicUrl);

        return affectedRows > 0;
    }

    /**
     * 删除
     * 删除指定类目以及其子类类目，实际上是隐藏了这些类目
     *
     * @param marketCategory 封装了要删除类目的信息的对象
     * @return boolean true表示删除成功，false表示删除失败
     * @author Chen_Feng
     * @since 2022/06/26 23:30
     */
    @Override
    public boolean deleteCategoryWithSub(MarketCategory marketCategory) {

        // 执行mapper操作
        int affectedRows = marketCategoryMapper.deleteCategoryWithSub(marketCategory.getId());

        if (affectedRows > 0) {
            return true;
        }
        return false;
    }

    /**
     * <<<<<<< HEAD
     * 根据categoryId查询categoryList、parentCategory、currentCategory
     *
     * @Auther leihao
     * @Date 16:21 2022/6/29
     * @Param
     * @Return
     **/
    @Override
    public GoodsCategoryVo getCategoryByPid(Integer id) {
        Integer pid = marketCategoryMapper.selectPidById(id);
        List<MarketCategory> brotherCategory = null;
        MarketCategory currentCategory = null;
        if (pid == 0) {
            //id是1级
            brotherCategory = marketCategoryMapper.selectByPid(id);
            if (brotherCategory.size() > 0) {
                currentCategory = marketCategoryMapper.selectByPrimaryKey(brotherCategory.get(0).getId());
            }
        } else if (pid != 0) {
            brotherCategory = marketCategoryMapper.selectByPid(pid);
            currentCategory = marketCategoryMapper.selectByPrimaryKey(id);
        }

        MarketCategory parentCategory = marketCategoryMapper.selectByPrimaryKey(id);


        GoodsCategoryVo goodsCategoryVo = new GoodsCategoryVo();
        goodsCategoryVo.setBrotherCategory(brotherCategory);
        goodsCategoryVo.setCurrentCategory(currentCategory);
        goodsCategoryVo.setParentCategory(parentCategory);
        return goodsCategoryVo;
    }

    /**
     * @Auther leihao
     * @Date 16:55 2022/6/29
     * @Param
     * @Return
     **/
    @Override
    public WxGoodsListVo getCategoryListByCategoryId(Integer brandId, String keyword, Integer categoryId, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        WxGoodsListVo goodsListVo = new WxGoodsListVo();
        List<HotGoodsListDTO> list = null;
        if (brandId == null && keyword == null && categoryId != null) {
            list = goodsMapper.selectGoodsByCategoryId(categoryId);
        } else if (keyword != null) {
            keyword = keyword.trim();

            // 从principal中获取用户id，如果有则增加或更新搜索历史，无则忽略
            Subject subject = SecurityUtils.getSubject();
            if (subject.isAuthenticated()) {
                MarketUser user = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
                Integer userId = user.getId();
                if (!keyword.isEmpty()) {
                    List<MarketSearchHistory> marketSearchHistoryList  = searchHistoryMapper.selectSearchHistoryByKeywordAndUserId(keyword, userId);
                    if (marketSearchHistoryList.size() == 0) {
                        searchHistoryMapper.insertSearchHistory(keyword, userId);
                    } else {
                        ArrayList<Integer> searchHistoryIdList = new ArrayList<>();
                        for (MarketSearchHistory marketSearchHistory : marketSearchHistoryList) {
                            searchHistoryIdList.add(marketSearchHistory.getId());
                        }
                        searchHistoryMapper.updateUptateTime(searchHistoryIdList);
                    }
                }
            }

            keyword = "%" + keyword + "%";
            list = goodsMapper.selectGoodsByKeyword(keyword);
        } else if (brandId != null) {
            list = goodsMapper.selectGoodsBybrandId(brandId);
        }

        ArrayList<Integer> goodsIdList = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            goodsIdList.add(list.get(i).getId());
        }

        List<Integer> categoryIdList = new ArrayList<>();
        if (goodsIdList.size() > 0) {
            categoryIdList = goodsMapper.selectCategoryIdByGoodsIdList(goodsIdList);
        }
        List<MarketCategory> filterCategoryList = null;
        if (categoryId == null || categoryId == 0) {
            if (categoryIdList.size() > 0) {
                filterCategoryList = marketCategoryMapper.selectByCategoryIdList(categoryIdList);
            }
        } else {
            filterCategoryList = marketCategoryMapper.selectCategoryL2();
        }
        PageInfo<MarketCategory> pageInfo = new PageInfo(list);
        goodsListVo.setTotal((int) pageInfo.getTotal());
        goodsListVo.setPages(pageInfo.getPages());
        goodsListVo.setPage(pageInfo.getPageNum());
        goodsListVo.setLimit(pageInfo.getPageSize());
        goodsListVo.setFilterCategoryList(filterCategoryList);
        goodsListVo.setList(list);
        return goodsListVo;
    }

    /**
     * 获取所有的商品类目
     *
     * @return com.cskaoyan.bean.chenfeng.vo.CategoryIndexVo
     * @author Chen_Feng
     * @since 2022/06/29 13:57
     */
    @Override
    public CategoryIndexVo getCateGoryIndex() {

        // 执行查询操作
        List<MarketCategory> categoryList = marketCategoryMapper.selectCateGoryL1List();
        MarketCategory currentCategory = marketCategoryMapper.selectMinIdCategory();
        List<MarketCategory> currentSubCategory = marketCategoryMapper.selectByCategoryPid(currentCategory.getPid());

        // 图片路径处理
        addWebAddressforListCategoryUrl(categoryList);
        addWebAddressforListCategoryUrl(currentSubCategory);
        addWebAdressForSingleCategoryUrl(currentCategory);

        // 拼接
        CategoryIndexVo data = new CategoryIndexVo();
        data.setCategoryList(categoryList);
        data.setCurrentCategory(currentCategory);
        data.setCurrentSubCategory(currentSubCategory);

        // 返回数据
        return data;
    }

    /**
     * 获取指定的一级类目信息和其子类信息
     *
     * @param id
     * @return com.cskaoyan.bean.chenfeng.vo.CategoryIndexVo
     * @author Chen_Feng
     * @since 2022/06/29 15:24
     */
    @Override
    public CurrentCategoryVo getCurrentCateGory(Integer id) {

        // 查询数据库
        MarketCategory currentCategory = marketCategoryMapper.selectByCategoryId(id);
        List<MarketCategory> currentSubCategory = marketCategoryMapper.selectByCategoryPid(currentCategory.getId());

        // 处理图片路径
        addWebAdressForSingleCategoryUrl(currentCategory);
        addWebAddressforListCategoryUrl(currentSubCategory);

        // 组合信息
        CurrentCategoryVo data = new CurrentCategoryVo();
        data.setCurrentCategory(currentCategory);
        data.setCurrentSubCategory(currentSubCategory);

        return data;
    }

    /**
     * 处理单个对象中图片路径
     *
     * @param currentCategory
     * @return void
     * @author Chen_Feng
     * @since 2022/06/29 14:55
     */
    private void addWebAdressForSingleCategoryUrl(MarketCategory currentCategory) {
        String iconUrl = currentCategory.getIconUrl();
        String picUrl = currentCategory.getPicUrl();
        if (iconUrl != null && !iconUrl.startsWith("http://") && !iconUrl.startsWith("https://")) {
            currentCategory.setIconUrl(webAdress + iconUrl);
        }
        if (picUrl != null && !picUrl.startsWith("http://") && !picUrl.startsWith("https://")) {
            currentCategory.setPicUrl(webAdress + picUrl);
        }
    }

    /**
     * 处理集合中对象中图片url的路径
     *
     * @param categoryList
     * @return void
     * @author Chen_Feng
     * @since 2022/06/29 14:54
     */
    private void addWebAddressforListCategoryUrl(List<MarketCategory> categoryList) {
        for (MarketCategory categoryListEntity : categoryList) {
            addWebAdressForSingleCategoryUrl(categoryListEntity);
        }
    }

    /**
     * 获得sortOrder
     *
     * @return byte
     * @author Chen_Feng
     * @since 2022/06/29 11:48
     */
    private byte getSortOrder(MarketCategory marketCategory) {
        byte result = 1;
        List<MarketCategory> maxSortOrderCategoryList = marketCategoryMapper.selectCategoryWithMaxSortOrder(marketCategory);

        if (maxSortOrderCategoryList == null || maxSortOrderCategoryList.isEmpty()) {
            return result;
        }

        result = maxSortOrderCategoryList.get(0).getSortOrder();
        if (result == Byte.MAX_VALUE) {
            return Byte.MAX_VALUE;
        }

        result = (byte) (result + 1);
        for (MarketCategory category : maxSortOrderCategoryList) {
            if (Objects.equals(category.getId(), marketCategory.getId())) {
                result = category.getSortOrder();
                break;
            }
        }
        return result;
    }

}
